package com.tramp.frame.server.pageplugin;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.tramp.frame.server.thread.ThreadCacheAbstract;

@Component
public class PageInfoHolder extends ThreadCacheAbstract<PageInfo> {

	private static final long serialVersionUID = 6776569773157224287L;

	private String dialect = "mysql";

	public PageInfoHolder() {
		super("PageInfoModel");
	}

	public String getDialect() {
		return dialect;
	}

	public PageInfo getPageInfo() {
		return this.getCache();
	}

	private void setPageInfoModel(PageInfo pageInfo) {
		this.setCache(pageInfo);
	}

	public void setPageInfoModel(Integer start, Integer limit) {
		PageInfo info = new PageInfo();
		info.setStart(start);
		info.setLimit(limit);
		this.setPageInfoModel(info);
	}

	public void setSqlId(String sqlId, Boolean excuteCount) {
		if (null == sqlId || "".equals(sqlId)) {
			return;
		}
		PageInfo info = getPageInfo();
		if (null == info) {
			info = new PageInfo();
		}
		info.setExcuteCount(excuteCount);
		info.setSqlId(sqlId);
		this.setPageInfoModel(info);
	}

	public void setTotalCount(Integer count) {
		Integer myCount = 0;
		if (null != count) {
			myCount = count;
		}
		PageInfo info = getPageInfo();
		if (null == info) {
			info = new PageInfo();
		}
		info.setTotal(myCount);
		this.setPageInfoModel(info);
	}

	public Boolean isNeedPage(String sqlId) {
		if (null == sqlId || "".equals(sqlId)) {
			return false;
		}
		PageInfo info = getPageInfo();
		//如果没有设置sqlId，则不分页
		if (null == info || StringUtils.isBlank(info.getSqlId())) {
			return false;
		}

		return !(null == info.getStart() || info.getStart() < 0 || null == info.getLimit() || info.getLimit() <= 0
				|| !sqlId.endsWith(info.getSqlId()));
	}

	public Boolean excuteCount() {
		PageInfo info = getPageInfo();
		return info.getExcuteCount();
	}

	public Integer getPageCount() {
		PageInfo info = getPageInfo();
		if (null == info) {
			return null;
		}
		else if (null == info.getTotal()) {
			return 0;
		}
		else {
			return info.getTotal();
		}
	}

	public String converterPageSql(String sqlId, String sql) {
		if (!isNeedPage(sqlId)) {
			return sql;
		}
		if ("mysql".equals(dialect)) {
			StringBuilder pageSql = new StringBuilder();
			pageSql.append(sql);
			pageSql.append(" limit ");
			pageSql.append(getPageInfo().getStart());
			pageSql.append(",");
			pageSql.append(getPageInfo().getLimit());
			return pageSql.toString();
		}
		else {
			return sql;
		}
	}
}
